package com.wsc.services.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis工具包
 */
public class RedisUtil {

    static JedisPool jedisPool;

    /**
     * 连接池
     * @return 连接池
     */
    public static JedisPool getJedisPool(){
        if(jedisPool == null){
            synchronized (RedisUtil.class){
                if (jedisPool == null){
                    JedisPoolConfig jpc = new JedisPoolConfig();
                    jpc.setMaxIdle(5);
                    jpc.setMaxTotal(20);
                    jpc.setMaxWaitMillis(5*1000);
                    jpc.setTestOnBorrow(true);
                    jedisPool = new JedisPool(jpc,"localhost",6379,10*1000,"305617");
                }

            }

        }
        return jedisPool;
    }

    /**
     * 添加数据
     * @param key 键
     * @param value 值
     */
    public static void set(String key,String value){
        Jedis jedis = null;
        try {
            jedis = getJedisPool().getResource();
            jedis.set(key, value);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (jedis != null) jedis.close();

        }
    }

    /**
     * 得到value
     * @param key 键
     * @return value
     */
    public static String get(String key){
        Jedis jedis = null;
        String rValue = null;
        try {
            jedis = getJedisPool().getResource();
            rValue = jedis.get(key);
            return rValue;
        }catch (Exception e){
            e.printStackTrace();
            return rValue;
        }finally {
            if (jedis != null) jedis.close();
        }
    }



}
